;*****************************************************************************************************
;+
; NAME:
;
;      eWSET (Enhanced WSET)
;
; PURPOSE:
;
;      This is the enhanced version of the standard IDL WSET
;      procedure. It selects the current active IGL window. The
;      index of the current IGL window is stored in the !IGL_D.window
;      global variable. See the IDL documentation of the WSET command
;      for more details.
;
; CALLING SEQUENCE:
;
;      eWSET, windowId
;
; ARGUMENTS:
;
;     WINDOWID:     The identifier of the window. Similar to the
;                   window_index argument of the WSET procedure.
;
;                 
; KEYWORD PARAMETERS:
;
;    None.
;
; PACKAGE:
;
;    Interactive Graphics Library (IGL)
;
; AUTHORS:
;
;        RAPHAEL SADOUN
;        Graduate Student
;        Institut d'Astrophysique de Paris
;        98 bis boulevard Arago
;        75014 PARIS FRANCE
;        E-mail: raphael.sadoun@gmail.com
;
;
; MODIFICATION HISTORY:
;
;     Written by: Raphael Sadoun, 24 April 2012
;-
;*****************************************************************************************************
PRO eWSET, windowID

  COMPILE_OPT idl2, HIDDEN
  ON_ERROR, 2

  ;; Initialize global system variables
  IGL_InitSysVars

  ;; The default is to use id = 0
  IF (n_elements(windowID) EQ 0) THEN windowID = 0

  ;; Get the object reference of the requested window
  windowObjRefs = IGL_GetSysVars('windowObjRefs')

  IF windowID EQ -1 THEN BEGIN ; We need to locate a valid IGL window
     
     valids = where(OBJ_ISA_VALID(windowObjRefs,'IGL_Window'),count)     
     
     IF count GT 0 THEN targetWindow = windowObjRefs[valids[count-1]] $ ; If there is one available, this is our target                                       
     ELSE BEGIN                                                         ; Otherwise, update the system variable to reflect this.
        
        IGL_SetSysVars, 'currentWindow', -1
        !IGL_D.window = -1
        RETURN
        
     ENDELSE
     
  ENDIF ELSE BEGIN
     
     ;; Make sure we have a valid identifier
     IF (windowID LT 0) OR (windowID GT 49) THEN Message, 'IGL window identifiers must be between 0 and 49.'

     ;; Get the target window
     targetWindow = windowObjRefs[windowID]

  ENDELSE

  ;; If this is a valid window, we make it the current IGL window.
  IF OBJ_ISA_VALID(targetWindow,'IGL_Window') THEN BEGIN

     ;; Get window's properties
     targetWindow -> GetProperty, Window_ID=wID, Xsize=xsize, Ysize=ysize

     ;; Set the internal variable to point to the new window reference
     IGL_SetSysVars, 'currentWindow', wID

     ;; Update the IGL system variables
     !IGL_D.window = wID
     !IGL_D.x_size = xsize
     !IGL_D.y_size = ysize
     
     
  ENDIF ELSE Message, 'IGL Window is closed and unavailable.'

END
